<?php
namespace app\admin\model;

use Db;

/**
 * 用户分类表
 */
class User extends Base
{
    protected $autoWriteTimestamp = true;
    protected $insert             = ['status' => 1, 'tid' => 1];
    protected $update             = ['tid' => 1]; //后台用户
    protected $readonly           = ['user_name']; //user_name 不让修改

    protected function setUserNameAttr($value)
    {
        return trim($value);
    }
    protected function setNicknameAttr($value)
    {
        return trim($value);
    }

    protected function setEmailAttr($value)
    {
        return trim($value);
    }

    protected function setLoginIpAttr()
    {
        return request()->ip();
    }

    protected function setPasswordAttr($value)
    {
        return self::editpassword($value);
    }

    public static function listpage($value = '')
    {
        return self::paginate(10);
    }

    protected static function init()
    {

        /**
         * 删去后
         */
        // self::afterDelete(function ($user) {
        //     //有子栏目 栏目中有文章时，不能删 &&与运算时就是两边同时成立时为真，|| 或时两边一个成立就是真
        //     if (Db::name('arctype')->where('pid', $user->id)->count() > 0 || Db::name('article')->where('typeid', $user->id)->count() > 0) {
        //         return false;
        //     }
        // });

        /**
         * 更新前
         */
        self::beforeUpdate(function ($user) {
            //自身，主管理员不让禁用
            if ($user->id == 1 || $user->id == UID) {
                if (isset($user->status) && $user->status == 0) {
                    return false;
                }
            }
        });

        /**
         * 删去前
         */
        self::beforeDelete(function ($user) {
            if ($user->id != 1 && $user->id != UID) { //主管理员不让删
                Db::name('auth_group_access')->where('uid', $user->id)->delete(); //删去管理员对应的权限
                Db::name('token_user')->where('id', $user->id)->delete(); //删去对应的后台token验证
            } else {
                return false;
            }
        });
    }

    public static function edit($post, $id = '0')
    {
        if ($id != 0 && !empty($post)) {
            $data = self::get($id);
            if (trim($post['password'])) {
                $data->password = $post['password'];
            }
            $data->nickname = $post['nickname'];
            $data->email    = $post['email'];
            $data->sex      = $post['sex'];
            $data->status   = $post['status'];

            if ($data->save() > 0) {
                return true;
            } else {
                return false;
            }
        }
    }

    /*
    登录数据处理
     */
    public static function login($username, $password)
    {
        $data = self::where('status', 1)->where('tid', 1)->where('user_name', $username)->find(); //tid 为 1的后台用户
        //echo self::editpassword($password);
        //print_r($data);exit;
        if (!empty($data) && $data['password'] === self::editpassword($password)) {
            //设置session,cookie
            session('userid', $data['id']);
            cookie('username', $data['user_name']);
            cookie('uid', $data['id']);
            if (!empty($data['nickname'])) {
                cookie('nickname', $data['nickname']);
            }
            //$write = $data['nickname'] ? $data['nickname'] : $data['user_name'];
            cookie('write', $data['nickname'] ? $data['nickname'] : $data['user_name']);

            $login_time = config('webconfig.login_time'); //配制文件中不存在时读取数据库
            if (!isset($login_time)) {
                $login_time = Db::name('webconfig')->where(['varname' => 'login_time'])->value('value');
            }

            $user_token = self::createToken($data['id'], 1, $login_time);
            session('user_token', $user_token);
            $ip = \Request::ip();
            //更新状态
            self::where(['id' => $data['id']])->update(['login_ip' => $ip, 'login_time' => time()]);

            $address = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=" . $ip); //淘宝ip
            $address = json_decode($address, true);

            $address = $address['data']['country'] . '--' . $address['data']['region'] . '--' . $address['data']['city'] . '--' . $address['data']['county'] . '--' . $address['data']['isp'];

            $address = str_replace('XX', '--', $address);
            $address = array_filter(array_unique(explode('--', $address)));
            $address = implode("-", $address);

            $loginlog = ['tid' => 1, 'uid' => $data['id'], 'ip' => \Request::ip(), 'address' => $address, 'update_time' => time()];
            Db::name('login_log')->data($loginlog)->insert();

            return true;
        }
        return false;
    }

    /**
     * 用户密码添加干扰字符串
     * @param   $password      要加的字符串
     * @param   $password_code 干扰参数
     * @return                 返回加密后的字符串
     */
    public static function editpassword($password, $password_code = 'lshi4AsSUrUOwWV')
    {
        return md5(md5($password) . md5($password_code));
    }

    /**
     * @Title: createToken
     * @Description: todo(登陆时生成用户token)
     * @param int $uid 用户id
     * @param int $type 类型【1、PC，2、移动端】
     * @param int $token_time token令牌时限【PC登陆超时】
     * @return string
     * @date 2017年9月16日
     * @throws
     */
    public static function createToken($uid, $type = '1', $token_time = '')
    {
        $token      = md5($uid . uniqid() . rand(100000000, 999999999));
        $token_time = time() + $token_time;
        $where      = [
            'uid'  => $uid,
            'type' => $type,
        ];
        $isToken = Db::name('token_user')->where($where)->find();
        if (!empty($isToken)) {
            //存在token
            $data = [
                'token'       => $token,
                'token_time'  => $token_time,
                'update_time' => time(),
            ];
            Db::name('token_user')->where($where)->update($data);
        } else {
            $data = [
                'uid'         => $uid,
                'type'        => $type,
                'token'       => $token,
                'token_time'  => $token_time,
                'update_time' => time(),
            ];
            Db::name('token_user')->data($data)->insert();
        }
        return $token;
    }

}
